package sush.global.cammail;

import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import sush.global.cammail.actionbar.ActionBarActivity;
import sush.global.cammail.provider.Scheme;

public class TemplatesActivity extends ActionBarActivity {
	private ListView _templatesList;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitle(getResources().getString(R.string.templates_title_pref));
		super.addMenuIds(new int[] {R.id.menu_back, R.id.menu_add});
		
		setContentView(R.layout.templates_list);
		
		loadData();
	}
	
	private void loadData() {
		Cursor cursor = getContentResolver().query(
				Scheme.getTemplateTable().getContentUri(),
				null,
				null,
				null,
				null);
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
				R.layout.listitem_with_add,
				cursor,
				new String[] { Scheme.getTemplateTable().COLUMN_NAME_NAME },
				new int[] { R.id.title });
		
		_templatesList = (ListView)findViewById(R.id.list);
		_templatesList.setAdapter(adapter);
		_templatesList.setOnItemClickListener(itemClicked);
	}
	
	public void deleteClicked(View view) {
		int position = _templatesList.getPositionForView((View)view.getParent());
		final Cursor cursor = ((SimpleCursorAdapter)_templatesList.getAdapter()).getCursor();
		cursor.moveToPosition(position);
		final ContentValues values = new ContentValues();
		DatabaseUtils.cursorRowToContentValues(cursor, values);
		
		AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
		alertDialog.setTitle("Are you sure?");
		alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				String templateId = values.getAsString(Scheme.getTemplateTable()._ID);
				deleteFieldsForTemplate(templateId);
				String whereClause = Scheme.getTemplateTable()._ID + "=?";
				getContentResolver().delete(
						Scheme.getTemplateTable().getContentUri(),
						whereClause,
						new String[] { templateId });
			}
		});
		alertDialog.setNegativeButton("Cancel", null);
		alertDialog.show();
	}
	
	private void deleteFieldsForTemplate(String templateId) {
		String whereClause = Scheme.getFieldTable().COLUMN_NAME_IDTEMPLATE + "=?";
		String[] whereArgs = new String[] { templateId };
		ContentResolver content = getContentResolver();
		Cursor cursor = content.query(Scheme.getFieldTable().getContentUri(),
				new String[] {Scheme.getFieldTable()._ID},
				whereClause,
				whereArgs,
				null);
		
		while(cursor.moveToNext()) {
			String _fieldId = cursor.getString(0);
			content.delete(Scheme.getDropDownValueTable().getContentUri(),
					Scheme.getDropDownValueTable().COLUMN_NAME_IDFIELD + "=?",
					new String[] { _fieldId });
		}
		
		content.delete(Scheme.getFieldTable().getContentUri(), whereClause, whereArgs);
	}
	
	private OnItemClickListener itemClicked = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> list, View view, int position, long id) {
			Cursor cursor = ((SimpleCursorAdapter)_templatesList.getAdapter()).getCursor();
			cursor.moveToPosition(position);
			final ContentValues values = new ContentValues();
			DatabaseUtils.cursorRowToContentValues(cursor, values);
			
			Intent intent = new Intent(TemplatesActivity.this, TemplateActivity.class);
			intent.putExtra("template_id", values.getAsInteger(Scheme.getTemplateTable()._ID));
			startActivity(intent);
		}
	};
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.add, menu);
        return super.onCreateOptionsMenu(menu);
    }
	
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch(item.getItemId()) {
    		case R.id.menu_back:
    			finish();
    			break;
    		case R.id.menu_add:
    			Intent intent = new Intent(this, TemplateActivity.class);
    			intent.putExtra("template_id", -1);
    			startActivity(intent);
    			break;
    		case R.id.home_button:
    			Intent intentHome = new Intent(this, MainActivity.class);
    			intentHome.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    			intentHome.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    			startActivity(intentHome);
    			break;
    		default:
    			return super.onOptionsItemSelected(item);
    	}
    	return true;
    }
}
